<template>
	<view class="recycle_form-container">

		<u-form :error-type="['toast']" :model="form" ref="uForm">
			<view class="recycle-devices">
				<u-form-item prop="sn">
					<u-field label="商品名称" required type="input" v-model="form.name" maxlength="20"
						placeholder-style="#999999" placeholder="请输入商品名称" :border-bottom="false" label-width="200"
						:field-style="{
				          fontSize: '28rpx',
				          color: '\#333333'
				      }" />
				</u-form-item>

				<view>
					<u-form-item prop="classify">
						<picker mode="date" :value="form.date" @change="onSelectDateChange">
							<u-field required v-model="form.date" label="购买时间" placeholder-style="#999999"
								placeholder="请选择购买时间" :border-bottom="false" label-width="200" :field-style="{
						      fontSize: '28rpx',
						      color: '\#333333'
						  }" disabled>
								<u-icon name="arrow-right" slot="right" color="#707070" size="28" />
							</u-field>
						</picker>
					</u-form-item>
				</view>


				<u-form-item prop="sn">
					<u-field required label="购买价格" type="input" v-model="form.price" maxlength="20"
						placeholder-style="#999999" placeholder="请输入购买价格" :border-bottom="false" label-width="200"
						:field-style="{
				          fontSize: '28rpx',
				          color: '\#333333',
						  width: '120rpx'
				      }">
						<text slot="right">元</text>
					</u-field>
				</u-form-item>

				<u-form-item prop="sn">
					<u-field required label="期待价值" type="input" v-model="form.wantPrice" maxlength="20"
						placeholder-style="#999999" placeholder="请输入期待价值" :border-bottom="false" label-width="200"
						:field-style="{
				          fontSize: '28rpx',
				          color: '\#333333'
				      }">
						<text slot="right">元</text>
					</u-field>
				</u-form-item>
			</view>

			<!-- 备注说明 -->
			<view class="recycle-remark">
				<u-form-item :border-bottom="false">
					<view class="flex1">
						<view>备注说明<text class="muted ml10">(选填)</text></view>
						<u-field v-model="form.remark" type="textarea" height="160" label-width="0" :clearable="false"
							:border-bottom="false" maxlength="240" style="line-height: 1.2em;" />
					</view>
				</u-form-item>
			</view>


			<!-- 拍照凭证 -->
			<view class="recycle-picture">
				<u-form-item :border-bottom="false">
					<view class="flex1">
						<view @tap="isShowPictureModal = true">
							<text>上传凭证</text>
							<text class="muted ml10">(请上传图片凭证)</text>
							<u-icon class="ml10" name="question-circle" color="#999999" />
						</view>
						<view class="row wrap" style="column-gap: 80rpx;row-gap: 40rpx;">
							<u-upload v-for="(item,i) in imgText" :key="i" :ref="'upload'+i" width="170" height="170"
								:auto-upload="false" :custom-btn="true" :border-bottom="false" :show-progress="false"
								:max-count="1" :multiple="false" @on-remove="handlePictureRemove(i)"
								@on-choose-complete="list=>handlePictureUpload(i,list)">
								<view slot="addBtn" class="recycle-picture-button--upload">
									<u-icon name="/static/images/icon_camera.png" width="54" />
									<view class="xs normal"><text v-if="item.require"
											style="color: #FF2C3C;">*</text>{{item.name}}</view>
								</view>
							</u-upload>
						</view>

					</view>
				</u-form-item>
			</view>
		</u-form>



		<!-- Submit -->
		<view class="mt20 row" @tap="confirmProtocol=!confirmProtocol">
			<u-checkbox v-model="confirmProtocol" shape="circle" />
			同意签署<text @tap.stop="isShowPopup=true;" style="color: var(--primary-color);">《趣换协议》</text>
		</view>
		<view class="recycle-submit" @tap="onSubmit">提交订单</view>

		<u-modal v-model="isShowPopup" width="90%" :show-title="false">
			<scroll-view scroll-y style="max-height: 70vh;padding:20rpx;box-sizing: border-box;">
				<rich-text :nodes="quHuanXieYi"></rich-text>
			</scroll-view>
		</u-modal>

		<u-modal v-model="isShowTipsModal" :show-title="false" @confirm="modalConf" confirm-text="知道了">
			<view class="recycle-tips-modal">
				<image src="../../static/images/waitting.png" mode="widthFix" class="img"></image>
				<view class="text">请耐心等待估价</view>
			</view>
		</u-modal>
	</view>
</template>


<script>
	import {
		getGoodsCategory,
		getGoodsParams,
		getSearchGoods,
		postSubmitOrder,
		getQuHuanXieYi
	} from '@/api/recycle.js'
	import {
		uploadFile
	} from '@/utils/tools.js';



	const getCurrentDate = () => {
		const date = new Date()
		const y = date.getFullYear()
		const m = date.getMonth() + 1
		const d = date.getDate()
		return `${y}-${m > 9 ? m : ('0' + m)}-${d > 9 ? d : ('0' + d)}`
	}

	export default {
		data() {
			return {
				mode: 'recycle', // 换租 || 回收
				// 表单数据
				form: {
					remark: '', // 备注
					pictures: new Array(6).fill(null), // 图片
					name: '',
					price: null,
					wantPrice: null,
					name: '',
					date: getCurrentDate()
				},
				isShowPopup: false,
				confirmProtocol: false,
				isMEID: false, // 是否需要MEID的输入
				quHuanXieYi: null,

				showClassPopup: false, // 弹出层 -> 分类
				showPopupType: 1, // 弹出层类型[一级分类 ｜ 二级分类]
				showModelPopup: false, // 弹出层 -> 型号
				oneClassifyList: [], // 一级分类列表
				twoClassifyList: [], // 二级分类列表
				goodsList: [], // 设备列表
				goodsParamsList: [], // 设备规格列表
				isShowPictureModal: false, // 拍照凭证说明 Tips
				isShowTipsModal: false,
				imgText: [{
					require: true,
					name: '商品正面图片'
				}, {
					require: true,
					name: '商品背面图片'
				}, {
					require: true,
					name: '商品左侧图片'
				}, {
					require: true,
					name: '商品右侧图片'
				}, {
					require: true,
					name: '商品视频'
				}, {
					require: false,
					name: '商品发票'
				}]
			}
		},

		computed: {
			// 品牌分类
			classify() {
				const form = this.form;
				return `${form.class_one}${form.class_one ? ' - ' : ''}${form.class_two}`;
			},
			// 型号名称
			model() {
				const model = this.goodsList.find(item => item.id == this.form.devices) || {};
				return model.name || '';
			}
		},

		methods: {
			modalConf() {
				uni.redirectTo({
					url: "/bundle/pages/recycle_form/recycle_form"
				})
			},
			onSelectDateChange(e) {
				this.form.date = e.detail.value
			},
			// 分类选择弹出层
			handleClassifyPopup() {
				console.log("Classify ...");
				this.showClassPopup = true;
				const mode = this.showPopupType;

				this.form.class_one ?
					this.showPopupType = 2 :
					this.showPopupType = 1;
			},

			// 选择分类一
			handleSelectClassOne(item) {
				this.form.class_oneID = item.id;
				this.goodsParamsList = [];
				this.isMEID = false;
				this.$set(this.form, 'class_one', item.name);
				getGoodsCategory({
					pid: item.id
				}).then(res => {
					if (res.code != 1) return;
					this.twoClassifyList = res.data;
				});
				// 清空分类二数据
				if (this.form.class_two) this.$set(this.form, 'class_two', '');
				this.showPopupType = 2;
			},

			// 选择分类二
			handleSelectClassTwo(item) {
				this.form.class_twoID = item.id;
				this.goodsParamsList = [];
				this.isMEID = false;
				this.$set(this.form, 'class_two', item.name);
				getGoodsCategory({
					cid: item.id
				}).then(res => {
					if (res.code != 1) return;
					this.goodsList = res.data || [];
					const params = {};
					this.goodsList.forEach(item => params[item.id] = {});
					this.$set(this.form, 'params', params);
				});
				this.showClassPopup = false;
			},

			// 点击选择型号名称
			onSelectModel() {
				if (!this.form.class_two) return uni.showToast({
					title: '请先选择品牌分类',
					icon: 'none'
				});
				this.showModelPopup = true;
			},

			// 点击搜索型号
			onSearchModel() {
				const form = this.form;
				getSearchGoods({
					cid: form.class_twoID,
					goods_name: form.search
				}).then(res => {
					if (res.code != 1) return;
					this.goodsList = res.data || [];
					const params = {};
					this.goodsList.forEach(item => params[item.id] = {});
					this.$set(this.form, 'params', params);
				});
			},

			// 选择型号
			handleSelectDevice(id) {
				this.isMEID = false;
				this.showModelPopup = false;
				this.$set(this.form, 'devices', id);
				getGoodsParams({
					re_id: id
				}).then(({
					code,
					data
				}) => {
					if (code != 1) return;
					this.goodsParamsList = data.goods_item;
					this.isMEID = !!(data.is_meid * 1);

					this.goodsParamsList.forEach(item => {
						this.$set(this.form.params[this.form.devices], item.id, '');
					});
				});
			},

			// 选择设备规格
			handleSelectParams(key, value) {
				this.$set(this.form.params[this.form.devices], key, value);
			},

			// 图片上传
			handlePictureUpload(i1, lists) {
				uni.showLoading({
					title: '正在上传中...',
					mask: true
				});

				const file = {
					...lists[0]
				};
				try {
					uploadFile(file.url).then(res => {
						uni.hideLoading();
						this.form.pictures[i1] = res.url;
					}).catch(err => {
						uni.hideLoading();
						this.$refs['upload' + i1][0].clear();
						this.$toast({
							title: err.msg || "上传失败"
						});
					});
				} catch (e) {
					uni.hideLoading();
					this.$toast({
						title: "上传失败"
					});
				}
			},

			// 图片删除
			handlePictureRemove(index) {
				this.form.pictures[index] = null;
			},

			// 表单提交
			onSubmit() {
				const form = this.form;
				if (!form.name) return this.$toast({
					title: '请输入商品名称'
				});
				if (!form.price) return this.$toast({
					title: '请输入商品原价'
				});
				if (!form.wantPrice) return this.$toast({
					title: '请输入期望价格'
				});
				if (form.pictures.some((v, i) => i < 5 && v == null)) return this.$toast({
					title: '请上传完整商品图片和视频'
				});
				if (!this.confirmProtocol) return this.$toast({
					title: '请签署《趣换协议》'
				});
				const field = {
					goods_name: form.name,
					remarks: form.remark,
					buy_time: form.date,
					buy_money: form.price,
					yw_money: form.wantPrice,
					imges: form.pictures.filter(v => v != null),
				}
				postSubmitOrder(field).then(res => {
					if (res.code != 1) return this.$toast({
						title: res.msg
					});
					this.isShowTipsModal = true;
				})
				// uni.navigateTo({
				// 	url: '/bundle/pages/recycle_price/recycle_price' +
				// 		'?order=' + JSON.stringify(field) +
				// 		'&mode=' + this.mode
				// });
			},
		},

		onLoad(options) {
			this.mode = options.mode || 'recycle';
			// 一级分类
			getGoodsCategory().then(res => {
				if (res.code != 1) return;
				this.oneClassifyList = res.data;
			});

			getQuHuanXieYi().then(res => {
				if (res.code != 1) return;
				this.quHuanXieYi = res.data;
			})
		},

		onReady() {}
	}
</script>


<style scoped lang="scss">
	@import "index.scss";

	/deep/.u-upload .u-list-item {
		margin: 0 !important;
	}
</style>